﻿namespace JxcLite.Shared;

/// <summary>
/// 商业伙伴挑选框组件。
/// </summary>
public class PartnerPicker : TablePicker<PartnerInfo>
{
    private IBaseDataService Service;

    /// <summary>
    /// 取得或设置商业伙伴类型（客户、供应商）。
    /// </summary>
    [Parameter] public string Type { get; set; }

    protected override async Task OnInitAsync()
    {
        await base.OnInitAsync();
        Service = await CreateServiceAsync<IBaseDataService>();
        Title = $"选择{Type}";
        Width = 700;
        Table.OnQuery = QueryPartnersAsync;
        Table.AddColumn(c => c.Name, true).Width(180);
        Table.AddColumn(c => c.ShortName).Width(100);
        Table.AddColumn(c => c.SccNo).Width(180);
        Table.AddColumn(c => c.Note).Width(200);
    }

    protected override Dictionary<string, object> GetPickParameters()
    {
        var parameters = base.GetPickParameters();
        parameters[nameof(Type)] = Type;
        return parameters;
    }

    protected override void OnValueChanged(List<PartnerInfo> items)
    {
        var value = SelectType == TableSelectType.Checkbox
                  ? string.Join(",", items.Select(d => d.Name))
                  : items?.FirstOrDefault()?.Name;
        if (ValueChanged.HasDelegate)
            ValueChanged.InvokeAsync(value);
    }

    private Task<PagingResult<PartnerInfo>> QueryPartnersAsync(PagingCriteria criteria)
    {
        criteria.SetQuery(nameof(PartnerInfo.Type), QueryType.Equal, Type);
        return Service.QueryPartnersAsync(criteria);
    }
}